/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Contrast.java
 *
 * Created on 14/02/2009, 18:30:52
 */
package edu.upf.grupE.interftest;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderedImageFactory;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URL;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.media.jai.*;
import javax.media.jai.registry.RIFRegistry;
import javax.swing.*;

/**
 *
 * @author Oscar
 */
public class Contrast2 extends javax.swing.JFrame {

    private static byte clamp(int value) {
        if (value < 0) {
            return 0;
        }
        if (value > 255) {
            return (byte) 255;
        }
        return (byte) value;
    }
    double zoom;
    int param1 = 0;
    int param2 = 255;
    ImageSelection im;
    String path;
    Icon imageIcon;
    int r;
    int g;
    int b;
    int contrast;
    int brightness;
    //Icon imageIcon = new ImageIcon(getClass().getResource("/img/ima_new_paisaje_001.jpg"));

    private ImageIcon scale(Image src, double scale) {
        int w = (int) (scale * src.getWidth(this));
        int h = (int) (scale * src.getHeight(this));
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage dst = new BufferedImage(w, h, type);
        Graphics2D g2 = dst.createGraphics();
        g2.drawImage(src, 0, 0, w, h, this);
        g2.dispose();
        return new ImageIcon(dst);
    }

    /** Creates new form Contrast */
    public Contrast2(ImageSelection im, String path, int a) throws MalformedURLException, IOException {
        this.im = im;
        this.path = path;

        File f = new File(path);
        BufferedImage img = ImageIO.read(f);

        int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();

        for (int y = 0; y < img.getHeight(); y++) {

            for (int x = 0; x < img.getWidth(); x++) {

                int pixel = pixels[x + (y * img.getWidth())];

                r = ((pixel << 8) >> 24) & 0xFF;
                g = ((pixel << 16) >> 24) & 0xFF;
                b = ((pixel << 24) >> 24) & 0xFF;
            }
        }
        PlanarImage ima = (PlanarImage) JAI.create("fileload", path);

        setColor(ima,r,g,b,contrast,brightness);
        imageIcon = new ImageIcon(path);
        initComponents();
        if (a == 1) {
            SampleDescriptor sampleDescriptor = new SampleDescriptor();
            OperationDescriptor odesc = sampleDescriptor;
            RenderedImageFactory rif = sampleDescriptor;

            String operationName = "sample";
            String productName = "com.mycompany";
            OperationRegistry or = JAI.getDefaultInstance().getOperationRegistry();
            or.registerDescriptor(odesc);
            RIFRegistry.register(or, operationName, productName, rif);
        }
    }

    public static PlanarImage setColor(PlanarImage source,
            int red, int green, int blue,
            float contrast,
            float brightness) {

// Setup the parameter block for the source image and
// the three parameters for the mean operation
        ParameterBlock mpb = new ParameterBlock();
        mpb.addSource(source); // The source image
        mpb.add(null); // null ROI means whole image
        mpb.add(1); // check every pixel horizontally
        mpb.add(1); // check every pixel vertically
// Perform the mean operation on the source image
        PlanarImage meanImage = JAI.create("mean", mpb, null);
// Retrieve the mean pixel value
        double[] mean = (double[]) meanImage.getProperty("mean");
// Average the mean of all bands
        double sum = 0.0D;
        for (int i = 0; i < mean.length; i++) {
            sum += mean[i];
        }
        int average = (int) sum / mean.length;

// Create the lookup table based on the average mean
        byte[][] lut = new byte[3][256];
        for (int i = 0; i < 256; i++) {
            lut[0][i] = clamp((average + (int) ((i - average) * contrast)) + red + (int) brightness);
            lut[1][i] = clamp((average + (int) ((i - average) * contrast)) +
                    green + (int) brightness);
            lut[2][i] = clamp((average + (int) ((i - average) * contrast)) + blue + (int) brightness);
        }
        LookupTableJAI lookup = new LookupTableJAI(lut);
// Setup the parameter block for the lookup operation
        ParameterBlock pb = new ParameterBlock();
        pb.addSource(source);
        pb.add(lookup);

// Return the resulting image
        return JAI.create("lookup", pb, null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() throws MalformedURLException {

        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jXLabel2 = new org.jdesktop.swingx.JXLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jSlider2 = new javax.swing.JSlider();
        jTextField3 = new javax.swing.JTextField();
        setSize(500, 500);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Brigthness and Contrast");

        jXLabel1.setText("Contrast");

        jXLabel2.setText("Brightness");

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField2.setEnabled(false);

        ImageIcon icon = new ImageIcon(new URL("file:/" + path));
        int x = icon.getIconWidth();
        int y = icon.getIconHeight();
        Dimension fram = getSize();

        float a1 = (float) fram.width;
        float x2 = a1 / x;
        float y2 = (float) fram.height / y;
        float z = Math.min(x2, y2);

        zoom = 0.8 * z;
        ImageIcon reduced = scale(icon.getImage(), zoom);
        jLabel1.setIcon(reduced);

        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {

            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jSlider2.addChangeListener(new javax.swing.event.ChangeListener() {

            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider2StateChanged(evt);
            }
        });

        jTextField3.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap(21, Short.MAX_VALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(jXLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(18, 18, 18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(32, 32, 32).addComponent(jButton1).addGap(18, 18, 18).addComponent(jButton2)).addGroup(layout.createSequentialGroup().addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)).addGroup(layout.createSequentialGroup().addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))).addGroup(layout.createSequentialGroup().addGap(99, 99, 99).addComponent(jLabel1))).addContainerGap(72, javax.swing.GroupLayout.PREFERRED_SIZE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(26, 26, 26)).addGroup(layout.createSequentialGroup().addGap(95, 95, 95).addComponent(jLabel1).addGap(62, 62, 62).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup().addComponent(jXLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)).addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton2).addComponent(jButton1))).addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void repaint() {
        // Beware of a race condition when Swing tries to repaint
        // before we've finished initialization.
        if (imageIcon instanceof IconJAI) {
            RenderedImage previousImage = ((IconJAI) imageIcon).getImage();
            if (previousImage instanceof PlanarImage) {
                ((PlanarImage) previousImage).dispose();
            }
        }
        imageIcon = new IconJAI(process());

        jLabel1.setIcon(imageIcon);
        Dimension iconSize = new Dimension(imageIcon.getIconWidth(),
                imageIcon.getIconHeight());
        jLabel1.setPreferredSize(iconSize);
        jLabel1.revalidate();


    }

    public PlanarImage process() {

        PlanarImage im = (PlanarImage) JAI.create("fileload", path);

        ParameterBlock pb = new ParameterBlock();
        Interpolation interp = Interpolation.getInstance(
                Interpolation.INTERP_BILINEAR);
        float zom = (float) zoom;
        ParameterBlock params = new ParameterBlock();
        params.addSource(im);
        params.add(zom);         // x scale factor
        params.add(zom);         // y scale factor
        params.add(0.0F);         // x translate
        params.add(0.0F);         // y translate
        params.add(interp);       // interpolation method

        /* Create an operator to scale image1. */
        RenderedOp image2 = JAI.create("scale", params);
        pb.addSource(image2);
        pb.add(param1);
        pb.add(param2);
        return JAI.create("sample", pb);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        System.out.println("A");
        im.setIcon(imageIcon);
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jSlider2StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider2StateChanged
        // TODO add your handling code here:
        JSlider source = (JSlider) evt.getSource();
        int value = source.getValue();
        jTextField3.setText(Integer.toString(value));

        if (source == jSlider1) {
            param1 = value;
            if (value > jSlider2.getValue()) {
                jSlider2.setValue(value);
            }
        } else {
            param2 = value;
            if (value < jSlider1.getValue()) {
                jSlider1.setValue(value);
            }
        }
        repaint();
    }//GEN-LAST:event_jSlider2StateChanged

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        // TODO add your handling code here:
        JSlider source = (JSlider) evt.getSource();
        int value = source.getValue();
        jTextField2.setText(Integer.toString(value));

        if (source == jSlider1) {
            param1 = value;
            if (value > jSlider2.getValue()) {
                jSlider2.setValue(value);
            }
        } else {
            param2 = value;
            if (value < jSlider1.getValue()) {
                jSlider1.setValue(value);
            }
        }
        repaint();
    }//GEN-LAST:event_jSlider1StateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new Contrast().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JSlider jSlider2;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private org.jdesktop.swingx.JXLabel jXLabel2;
    // End of variables declaration//GEN-END:variables
}
